﻿using Microsoft.Extensions.Options;
using ServiceCore.Entity.Core;
using ServiceCore.Entity.Model;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace ServiceCore.WebApi.jwt
{
    public class GenerateJwt
    {
        private readonly JwtConfig _jwtConfig;
        public GenerateJwt(IOptions<JwtConfig> jwtConfig)
        {
            _jwtConfig = jwtConfig.Value;
        }
        /// <summary>
        /// 生成token
        /// </summary>
        /// <param name="sub"></param>
        /// <param name="customClaims">携带的用户信息</param>
        /// <returns></returns>
        public string GenerateEncodedTokenAsync(string sub, string refreshToken, UserInfo customClaims, ref int expires)
        {
            //创建用户身份标识，可按需要添加更多信息
            var claims = new List<Claim>
            {
                new Claim("userid", customClaims.Id.ToString()),
                new Claim("userName", customClaims.UserName),
                new Claim("refreshToken", refreshToken),
                new Claim("isAdmin", customClaims.IsAdmin.ToString()),
                new Claim(JwtRegisteredClaimNames.Sub, sub),
            };
            expires = _jwtConfig.Expired;

            //创建令牌
            var jwt = new JwtSecurityToken(
                issuer: _jwtConfig.Issuer,
                audience: _jwtConfig.Audience,
                claims: claims,
                notBefore: _jwtConfig.NotBefore,
                expires: DateTime.Now.AddHours(expires),
                signingCredentials: _jwtConfig.SigningCredentials);
            var access_token = new JwtSecurityTokenHandler().WriteToken(jwt);
            return access_token;
        }
    }
}
